<template>
	<scroll-view class="form-container bg" :scroll-y="true">
        <blueList
            @val="getBlueVal"
            :print="printRandom"
            :printData="printData"
            @print-finish="confirmLoading = false"
            @device-state="getDeviceState"
        ></blueList>
        <view v-if="activeTab === 0" class="margin-top-10">
            <jkFormCard title="基本信息" :show-right-icon="true">
                <u-icon slot="right" :name="isEdit ? 'close' : 'edit-pen-fill'" size="24" :color="isModify ? '#eee' : '#000'" @click="onEditBtn"></u-icon>
                <!--<u-icon slot="right" name="scan" size="24" @click="onScanBtn"></u-icon>-->
                <jk-form-item label="分类" :show-right-icon="false">
                    <view>{{ ruleForm.categoryName || '' }}</view>
                </jk-form-item>
                <jk-form-item label="品种" :show-right-icon="false">
                    <view>{{ ruleForm.productName || '' }}</view>
                </jk-form-item>
                <jk-form-item label="批号" :show-right-icon="false">
                    <view>{{ ruleForm.batchCode || '' }}</view>
                </jk-form-item>
                <jk-form-item label="成分" :show-right-icon="false">
                    <view>{{ ruleForm.ingredient || '' }}</view>
                </jk-form-item>
                <jk-form-item label="净重(KG)" :show-right-icon="isEdit" :show-star="true">
                    <view v-if="!isEdit">{{ ruleForm.suttle || '' }}</view>
                    <u-input v-else v-model="ruleForm.suttle" :customStyle="{paddingLeft: 0}" @change="onIptSuttleChange" :holdKeyboard="false" :adjustPosition="true" :cursorSpacing="30" type="digit" fontSize="28rpx" inputAlign="left" placeholder="净重(KG)" border="surround"></u-input>
                </jk-form-item>
                <jk-form-item label="纸管" :show-right-icon="isEdit" @click="onSelectItem('paperTubeList', '纸管', zgColorList)" :show-star="true">
                    <view>{{ ruleForm.paperTubeList ? ruleForm.paperTubeList.map(x => x.name).join() : '' }}</view>
                </jk-form-item>
                <jk-form-item label="外袋" :show-right-icon="isEdit" @click="onSelectItem('outerBagList', '外袋', wdColorList)" :show-star="true">
                    <view>{{ ruleForm.outerBagList ? ruleForm.outerBagList.map(x => x.name).join() : '' }}</view>
                </jk-form-item>
                <jk-form-item label="内袋" :show-right-icon="isEdit" @click="onSelectItem('innerBagList', '内袋', ndColorList)" :show-star="true">
                    <view>{{ ruleForm.innerBagList ? ruleForm.innerBagList.map(x => x.name).join() : '' }}</view>
                </jk-form-item>
                <jk-form-item label="扎线" :show-right-icon="isEdit" @click="onSelectItem('bundleList', '扎线', zxColorList)" :show-star="true">
                    <view>{{ ruleForm.bundleList ? ruleForm.bundleList.map(x => x.name).join() : '' }}</view>
                </jk-form-item>
                <jk-form-item label="通知单号" :show-right-icon="false">
                    <view>{{ ruleForm.packingPlanCode || '' }}</view>
                </jk-form-item>
            </jkFormCard>
            <view class="margin-top-30">
                <jkFormCard title="打印数量">
                    <!--<view slot="right" class="flex-start-center">
                        <text style="font-size: 24rpx;margin-right: 20rpx;">显示二维码</text>
                        <u-switch v-model="printData.showQrCode"></u-switch>
                    </view>-->
                    <input v-model="printData.printCount" :cursorSpacing="120" type="number" @input="onIptChange" border style="border: solid 1rpx #eee;border-radius: 8rpx;height: 84rpx;padding: 0 24rpx;" @blur="onBlur">
                </jkFormCard>
            </view>
        </view>
		<view class="fixed-footer1 margin-top-30">
            <button v-if="isEdit" @click="onSaveBtn" type="primary" :loading="confirmLoading" style="width: 100%;" size="large">保存</button>
            <button v-else @click="onPrintBtn" type="primary" :disabled="!ruleForm.suttle || !ruleForm.paperTubeList.length || !ruleForm.outerBagList.length || !ruleForm.innerBagList.length || !ruleForm.bundleList.length || !ruleForm.productId || !printData.printCount || !deviceState" :loading="confirmLoading" style="width: 100%;" size="large">确定打印</button>
		</view>
		<u-datetime-picker
            v-model="selectDateTime"
            :show="selectDateTimePickerState"
            mode="datetime"
			:closeOnClickOverlay="true"
            @confirm="onConfirmBtnOfSelectPicker"
            @close="onCloseBtnOfSelectPicker"
			@cancel="onCloseBtnOfSelectPicker"
        ></u-datetime-picker>

        <jk-popup :show="showColorPopup" :title="`${selectColorTitle}颜色`" @close="onCloseColorPopup" @confirm="onConfirmPopup" :customStyle="{padding: '0 32rpx'}">
            <u-checkbox-group v-model="checkArr" size="21" iconPlacement="right" placement="column" :borderBottom="true" @change="onPopupCheckboxChange">
                <view style="height: 400px;overflow: auto;">
                    <u-checkbox v-for="item in popupOptionList" :key="item.id" labelSize="18" iconSize="20" :borderBottom="true"
                                :customStyle="{
                        height: '84rpx',
                        lineHeight: '84rpx',
                        display: 'flex',
                        alignItems: 'center',
                        padding: '0 24rpx',
                        borderBottom: 'solid 1rpx #e8eaec'
                    }"
                                labelColor="#17233d"
                        :label="item.name" :name="item.id" style=""></u-checkbox>
                </view>
            </u-checkbox-group>
        </jk-popup>
	</scroll-view>
</template>

<script>
import {
    productionPrdOrderBatchGet, productionPrdOrderBatchUpdate, spinTubeColorPage,
} from "../../../../api";
import {
    formatTime,
    showLoading, tipBar
} from "../../../../utils/jk-utils";
        import jkPopup from '../../../../jk-components/jk-popup';
    import jkFormCard from "../../../../jk-components/jk-from-card";
    import jkFormItem from "../../../../jk-components/jk-from-item";
    import jkPopupOption from "../../../../jk-components/jk-popup-option";
    import blueList from '../../electronicWeighing/blue-list';
    import getNoticeBatchInfo from "./getNoticeBatchInfo";
    let _this;
	export default {
	    mixins: [getNoticeBatchInfo],
		components: {
            blueList,
            jkPopupOption,
            jkFormCard,
            jkFormItem,
			jkPopup
		},
		data() {
			return {
                popupOptionList: [],
                printData: {
                    showQrCode: true,
                    printCount: 1,
                    data: {}
                },
                selectColorTitle: '',
                showColorPopup: false,
                printRandom: 0,
                realTimeVal: '',
                firstFocus: true,
				selectDateTime: '',
				selectDateTimePickerState: false,
				confirmLoading: false,
				activeTab: 0,
				tabList: ['基本信息', '包装信息'],
				dataId: null,
				ruleForm: {
                    "batchCode": "",
                    "batchId": 0,
                    "beforeNumber": 0,
                    "bundleList": [],
                    "empCode": "",
                    "empId": 0,
                    "empName": "",
                    "innerBagList": [],
                    "invalidDateTime": "",
                    "number": 0,
                    "outerBagList": [],
                    "packingPlanCode": "",
                    "packingPlanId": 0,
                    "paperTubeList": [],
                    "productCode": "",
                    "productId": 0,
                    "productName": "",
                    "productionDateTime": "",
                    "remark": "",
                    "suttle": 0,
                    "type": 0,
                    "warehouseCode": "",
                    "warehouseId": 0,
                    "warehouseName": "",
                    "workshopCode": "",
                    "workshopId": 0,
                    "workshopName": ""
				},
                operationType: '1',
                deviceState: false,
                isEdit: false,
                ndColorList: [],
                zxColorList: [],
                checkArr: [],
                wdColorList: [],
                zgColorList: [],
                isModify: false
			}
		},
		onLoad(e) {
            this.operationType =  e.type;
            this.dataId = e.code;
		},
		onShow() {
            _this = this;
			this.getDependentData();
		},
		methods: {
            onIptSuttleChange() {
                this.isModify = true;
            },
		    saveRequest() {
		        this.confirmLoading = true;
                productionPrdOrderBatchUpdate(this.ruleForm).then(res => {
                    this.confirmLoading = false;
                    this.isModify = false;
                    if (res.data.status === 200) {
                        this.isEdit = false;
                        tipBar('custom', '保存成功!', 'success');
                    }
                });
            },
            onConfirmPopup() {
                let arr = [];
                this.checkArr.forEach(x => {
                    this.popupOptionList.forEach(k => {
                        if (x === k.id) {
                            arr.push(k);
                        }
                    })
                })
                this.$set(this.ruleForm, this.colorKeyName, arr);
                this.showColorPopup = false;
                this.isModify = true;
            },
            onSelectItem(key, title, list) {
		        if (!this.isEdit) return;
		        this.selectColorTitle = title;
                this.checkArr = [];
                this.colorKeyName = key;
                this.colorPopupTitle = `选择${title}颜色`;
                this.showColorPopup = true;
                this.popupOptionList = JSON.parse(JSON.stringify(list));
            },
            onPopupCheckboxChange(e) {
                /*e.forEach(x => {
                    this.popupOptionList.forEach(k => {
                        if (x === k.id) {
                            this.checkArr.push(k);
                        }
                    })
                })*/
            },
            onCloseColorPopup() {
                this.showColorPopup = false;
            },
            onSaveBtn() {
                this.saveRequest();
            },
            onEditBtn() {
		        if (!this.isModify) {
                    this.isEdit = !this.isEdit;
                } else {
		          tipBar('custom', '保存后再操作!', 'error');
                }
            },
            getDeviceState(e) {
                this.deviceState = e;
            },
            onPrintBtn() {
                this.printRandom = Math.random();
                this.$set(this.printData, 'data', JSON.parse(JSON.stringify(this.ruleForm)));
                this.confirmLoading = true;
            },
		    getBlueVal(v) {
                // 修正this，否则指向会有问题
                _this.realTimeVal = v;
                wx.showToast({
                    title: `称重数据：${_this.realTimeVal}`,
                    icon: 'success'
                })
            },
            onBlur() {
                // this.firstFocus = false;
            },
            onIptChange(e) {
                this.$set(this.printData, 'printCount', Number(e.detail.value));
            },
            onClearWarehouse() {
                this.$set(this.ruleForm, 'warehouseId', '');
                this.$set(this.ruleForm, 'warehouseCode', '');
                this.$set(this.ruleForm, 'warehouseName', '');
            },
            // 纸管颜色
            getZgColorListRequest() {
                return spinTubeColorPage({
                    typeCode: "TUBE_COLOR"
                }).then(res => {
                    if (res.data.status === 200) {
                        this.zgColorList = res.data.res;
                    }
                })
            },
            // 外袋颜色
            getWdColorListRequest() {
                return spinTubeColorPage({
                    typeCode: "OUT_BAG_COLOR"
                }).then(res => {
                    if (res.data.status === 200) {
                        this.wdColorList = res.data.res;
                    }
                })
            },
            // 内袋颜色
            getNdColorListRequest() {
                return spinTubeColorPage({
                    typeCode: "INNER_BAG_COLOR"
                }).then(res => {
                    if (res.data.status === 200) {
                        this.ndColorList = res.data.res;
                    }
                })
            },
            // 扎线颜色
            getZxColorListRequest() {
                return spinTubeColorPage({
                    typeCode: "BUNDLE_COLOR"
                }).then(res => {
                    if (res.data.status === 200) {
                        this.zxColorList = res.data.res;
                    }
                })
            },
            onSelectTime(type) {
                this.timeType = type;
                this.selectDateTimePickerState = true;
            },
            onScanBtn() {
                let _this = this;
                // 允许从相机和相册扫码
                uni.scanCode({
                    success: function (res) {
                        let scanData = '';
                        try {
                            scanData = res.result;
                        } catch {
                            wx.showToast({
                                title: '无效的二维码',
                                icon: 'error'
                            })
                        }
                        if (scanData) {
                            wx.showModal({
                                title: '扫码结果',
                                content: `识别到计划:${scanData}`,
                                success(res) {
                                    if (res.confirm) {
                                        _this.getNoticeDetailRequest(scanData).then(res => {
                                            if (res.data.status === 200) {
                                                this.ruleForm = this.transferData(res.data.res);
                                            }
                                        });
                                    }
                                }
                            })
                        } else {
                            wx.showToast({
                                title: '二维码格式不符',
                                icon: 'error'
                            })
                        }
                    }
                });

            },
            onTransferNumber(e, type) {
                this.$set(this.ruleForm, type, Number(e));
            },
		    onDeleteTime() {
                this.$set(this.ruleForm, 'startSystemTime', null);
            },
            onOutputRatioBlur(e) {
                if (e > 1) {
                    this.$set(this.ruleForm, 'outputRatio', 1);
                }
            },
			onUpdateTime() {
				this.selectDateTimePickerState = true;
			},
			onCloseBtnOfSelectPicker() {
				this.selectDateTimePickerState = false;
			},
			onConfirmBtnOfSelectPicker(e) {
				this.$set(this.ruleForm, this.timeType, formatTime(e.value));
				this.selectDateTimePickerState = false;
			},
			onTabChange(e) {
				this.activeTab = e;
			},
            setData(res) {
                let resData = JSON.parse(JSON.stringify(res.data.res));
                this.ruleForm = resData;
                const str = resData.coarseSandList ? resData.coarseSandList.filter(x => x.typeName === '粗纱').map(x => x.productName).join(' ; ') : '';
                this.$set(this.ruleForm, 'ingredient', str);
            },
			async getDependentData() {
				showLoading(true);
				this.selectDateTime = formatTime(Date.now());
                await this.getZgColorListRequest();
                await this.getWdColorListRequest();
                await this.getNdColorListRequest();
                await this.getZxColorListRequest();
                if (this.dataId) await this.getNoticeDetailRequest(this.dataId).then(res => {
                    if (res.data.status === 200) {
                        this.ruleForm = this.transferData(res.data.res);
                    }
                });
                // this.$set(this.ruleForm, 'invalidDateTime', formatTime(Date.now()));
                // this.$set(this.ruleForm, 'productionDateTime', formatTime(Date.now()));
				showLoading(false);
			}
		}
	}
</script>

<style>

</style>
<style lang="scss" scoped>
	.machine-title {
		height: 42px;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #2d8cf0;
		border-radius: 12rpx;
		padding: 12rpx 24rpx;
		box-sizing: border-box;
        border: solid 1px #2d8cf0;
		text-align: center;
		font-size: 34rpx;
		font-weight: 500;
		margin: 10rpx;
	}

	.popup-content-box {
		padding: 32rpx;

		.popup-content-box-title {
			font-size: 34rpx;
			text-align: center;
			margin-bottom: 20rpx;
		}
	}
</style>
